package com.youdianstar.app.ui.pay

import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import com.youdianstar.app.R
import com.youdianstar.app.BR
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.network.BaseApiPagingObserver
import com.youdianstar.app.common.widget.adapter.FooterAdapter

import com.youdianstar.app.adapter.TransPagingAdapter
import com.youdianstar.app.databinding.ActivityPaymentRecordBinding
import com.youdianstar.app.util.DataAppManager
import kotlinx.coroutines.flow.collectLatest
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * File: RecordActivity
 * Author: 82149 Create: 2021/11/27 19:53
 * Changes (from 2021/11/27)
 * --------------------------------------------------
 * description: 流水
 * ---------------------------------------------------
 *
 */
class RecordActivity :BaseActivity<ActivityPaymentRecordBinding, WalletViewModel>(){
    override fun layoutId(): Int = R.layout.activity_payment_record

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): WalletViewModel {
        val model: WalletViewModel by viewModel()
        return model
    }

    private var mRecordPagingAdapter = TransPagingAdapter()

    override fun initViewLayout() {
        super.initViewLayout()
        mBinding.headBar.initTitle(this,getString(R.string.wallet_transactionRecord), showInner = false)

    }

    override fun initData() {
        super.initData()
        mBinding.run {
            rcRecord.adapter = mRecordPagingAdapter.withLoadStateFooter(FooterAdapter{
                //重新请求
                mRecordPagingAdapter.retry()
            })
            //刷新监听
            swRecord.setOnRefreshListener {
                mRecordPagingAdapter.refresh()
            }
            lifecycleScope.launchWhenCreated {
                mRecordPagingAdapter.loadStateFlow.collectLatest {
                    swRecord.isRefreshing = it.refresh is LoadState.Loading
                }
            }
            loadListData()
        }
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        mViewModel.listEventLiveData.observe(this, object :BaseApiPagingObserver(mBinding.rcRecord,isRecord = true){
            override fun onReload(v: View?) {
                loadListData()
            }
        })
    }

    override fun initClickEvent() {

    }

    override fun onResume() {
        super.onResume()
        if (DataAppManager.instance.billUpdateTag){
            DataAppManager.instance.billUpdateTag = false
            loadListData()
        }
    }

    private fun loadListData() {
        lifecycleScope.launchWhenCreated {
            mViewModel.getRecordList()?.collectLatest {
                //要测试这里是否能 获取到数据结果
                mRecordPagingAdapter.submitData(it)
            }
        }
    }

}